<template>
  <Modal
    ref="modalRef"
    v-model:visible="showModal"
    :centered="false"
    :width="650"
    cancelText="取消"
    okText="确认"
    title="授权人员管理"
    :destroyOnClose="true"
    @ok="handleSubmit"
  >
    <AuthorizedModal ref="authModelRef" :appId="appId" :subAppId="subAppId"></AuthorizedModal>
  </Modal>
  <RenewModal ref="renewModal" @submitSuccess="getAppInfo" />
  <Row :gutter="[24, 8]">
    <Col v-for="app in appList" :key="app.appId" :lg="6" :md="12">
      <Card
        :bordered="true"
        class="shadow-lg"
        style="height: 200px; min-width: 400px; width: 100%; border-radius: 10px"
      >
        <div class="flex h-full w-full">
          <div class="w-full">
            <span class="text-18px">{{ app.name }}</span>

            <div class="overflow-hidden mt-10px">
              <div class="float-left">在线人数:</div>
              <div
                class="
                  w-26px
                  h-26px
                  float-left
                  bg-sl-slBlue
                  rounded-1/2
                  flex
                  justify-center
                  text-12px
                  items-center
                  text-sl-slWhite
                  ml-10px
                "
              >
                {{ app.onlineNum }}
              </div>
            </div>
            <div class="flex mt-75px">
              <div
                v-per="'auth'"
                class="
                  transition
                  duration-500
                  ease-in-out
                  mr-10px
                  w-80px
                  h-35px
                  rounded-15px
                  bg-sl-slBlue
                  font-bold
                  flex
                  justify-center
                  items-center
                  cursor-pointer
                  transform
                  hover:scale-110
                  text-sl-slWhite
                "
                @click="openModal(app)"
              >
                授权
                <img class="ml-10px w-20px h-20px" src="../../../assets/svg/authorize.svg" />
              </div>
              <div
                v-if="app.type !== 1 && app.type !== 2 && app.paymentType === 'prePaid'"
                class="
                  transition
                  duration-500
                  ease-in-out
                  w-80px
                  h-36px
                  rounded-15px
                  bg-sl-slBlue
                  text-sl-slWhite
                  font-bold
                  flex
                  justify-center
                  items-center
                  cursor-pointer
                  transform
                  hover:scale-110
                "
                @click="renew(app)"
              >
                续订
                <img class="ml-10px w-23px h-23px" src="../../../assets/svg/renewal.svg" />
              </div>
            </div>
          </div>
          <div>
            <img :src="app.logo" class="h-100px w-100px rounded-50px" />
            <div
              v-if="app.type !== 1"
              class="
                text-right
                transition
                duration-500
                ease-in-out
                w-80px
                h-36px
                rounded-15px
                bg-red-500
                text-sl-slWhite
                font-bold
                flex
                justify-center
                items-center
                cursor-pointer
                transform
                hover:scale-110
                mt-35px
                ml-15px
              "
              @click="showUnsubscribe(app)"
            >
              退订
              <img class="ml-10px w-23px h-23px" src="../../../assets/svg/cancle.svg" />
            </div>
          </div>
        </div>
      </Card>
    </Col>
  </Row>
</template>

<script lang="ts" setup>
import { createVNode, ref } from 'vue';
import { Card, Col, Modal, Row } from 'ant-design-vue';
import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
import { getSubAppList, updateAppAuth } from '/@/api/system-mgmt/app-mgmt/app';
import { useUserStoreWithout } from '/@/store/modules/user';
import AuthorizedModal from './authorizedModal.vue';
import RenewModal from '/@/views/tenant-center/enterpriseAppManagement/component/RenewModal.vue';
import { releaseApp } from '/@/api/deployment-center/deployTask';
import { useMessage } from '/@/hooks/web/useMessage';
import { RoleRelation, SubAppInfo } from '/@/api/system-mgmt/app-mgmt/model/appModel';
import { useAuthState } from '/@/views/system-mgmt/authorization-mgmt/auth';

const userStore = useUserStoreWithout();
const tenantCode = userStore.getUserInfo.tenantCode;
let appList = ref<SubAppInfo[]>();
let authModelRef = ref();
let showModal = ref<boolean>(false);
let appId = ref<string>('');
const { createMessage } = useMessage();
let subAppId = ref<string>('');
const modalRef = ref();
const { getRoleMap } = useAuthState();
const getAppInfo = async function getSubAppListInfo() {
  appList.value = await getSubAppList();
};

getAppInfo();

const renewModal = ref();
const renew = (record) => {
  renewModal.value.openRenew(record);
};

function openModal(app) {
  appId.value = app.appId;
  subAppId.value = app.subAppId;
  showModal.value = true;
}

const showUnsubscribe = (app) => {
  Modal.confirm({
    title: '是否取消订阅此应用?',
    icon: createVNode(ExclamationCircleOutlined),
    content: createVNode('div', { style: 'color:red;' }, `即将退订（${app.name}）此次操作不可回退`),
    okText: '确认',
    cancelText: '取消',
    async onOk() {
      const res = await releaseApp({ appId: app.appId, tenantCode });
      createMessage.success('取消订阅成功');

      // logout when there is no app after unsubscribing
      if (!res.hasRemainedApp) {
        userStore.logout(true);
      } else {
        await getAppInfo();
      }
    },
    class: 'test',
  });
};

const handleSubmit = async () => {
  let roleMap: RoleRelation[] = [];
  getRoleMap().forEach((value, key) => {
    let temp: string[] = [];
    value.forEach((item) => {
      temp.push(item);
    });
    roleMap.push({ userId: key, roleIdList: temp });
  });

  await updateAppAuth({ appId: appId.value, appAuthForUsers: roleMap });
  createMessage.success('修改授权信息成功');
  showModal.value = false;
};
</script>

<style lang="less">
.saaslanding-appinfo {
  .ant-col {
    border: 1px solid;
  }
}
</style>
